package com.linkage.jz.bankruptcy.push;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.JsonObject;
import com.igexin.sdk.PushService;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;

import rx.schedulers.Schedulers;

public class GTPushService extends PushService {

    private static final String TAG = "GTPushService";
    public static final String CID_TAG = "save_cid";

    public static void saveCid(Context context, String clientid) {
        if (TextUtils.isEmpty(clientid))
            return;
        SPUtils.getInstance(Consts.SPNAME).put("saveCid", clientid);
        String localVersion = "";
        try {
            PackageInfo packageInfo = context.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            localVersion = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        LogUtil.d("TAG", "本软件的版本号。。" + localVersion);
        Network.getAPIService()
                .saveCid(clientid, localVersion, "0", Build.VERSION.SDK_INT + "",
                        android.os.Build.MODEL, android.os.Build.MANUFACTURER)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        Log.e(TAG, "保存Cid -> " + "json = " + json);
                        if (json.get("code").getAsInt() == 0) {
                            SPUtils.getInstance(Consts.SPNAME).put(CID_TAG, clientid);
                            JsonObject data = json.getAsJsonObject("data");
                            String cid = data.get("appInfoId").getAsString();

                            SPUtils.getInstance(Consts.SPNAME).put("appInfoId", cid);
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e(TAG, "保存Cid失败");
                    }
                });
    }
}